package main

import (
	"bufio"
	"fmt"
	"log"
	"os"
	"os/exec"
	"runtime"
	"strings"
	"time"

	"golang.org/x/sys/windows"
)

var variables = make(map[string]string)

func init() {
	// 启用Windows控制台的ANSI颜色支持
	if runtime.GOOS == "windows" {
		stdout := windows.Handle(os.Stdout.Fd())
		var originalMode uint32
		windows.GetConsoleMode(stdout, &originalMode)
		windows.SetConsoleMode(stdout, originalMode|windows.ENABLE_VIRTUAL_TERMINAL_PROCESSING)
	}
}

func showBanner() {
	red := "\033[1;31;40m"
	reset := "\033[0m"
	whiteRedBg := "\033[1;37;41m"

	fmt.Printf("%s  _    _ %s\n", red, reset)
	fmt.Printf("%s  \\    / %s\n", red, reset)
	fmt.Printf("%s   \\  /  %s\n", red, reset)
	fmt.Printf("%s    \\/   %s\n", red, reset)
	fmt.Printf("%s   _/\\_  %s\n", red, reset)
	fmt.Println()
	fmt.Printf("%sThis software has been verified by the Super X signature and is distributed without the permission of MADEPLUS Studios!%s\n", whiteRedBg, reset)
}

func clearScreen() error {
	var cmd *exec.Cmd
	if runtime.GOOS == "windows" {
		cmd = exec.Command("cmd", "/c", "cls")
	} else {
		cmd = exec.Command("clear")
	}
	cmd.Stdout = os.Stdout
	return cmd.Run()
}

func showHelp() {
	fmt.Println("ML语言帮助:")
	fmt.Println("  help              - 显示帮助信息")
	fmt.Println("  exit()           - 退出程序")
	fmt.Println("  println(\"内容\")   - 打印内容")
	fmt.Println("  x = \"值\"          - 定义变量")
	fmt.Println("  println(x)        - 打印变量值")
	fmt.Println("	LOADING()		-加载外部代码")
}

func executeCode(input string, infoLog *log.Logger) (shouldExit bool) {
	input = strings.TrimSpace(input)

	switch {
	case input == "":
		return false
	case input == "help":
		showHelp()
		return false 
	case input == "exit()":
		infoLog.Println("处理了一条程序级任务!")
		return true
	case strings.HasPrefix(input, "println(") && strings.HasSuffix(input, ")"):
		content := strings.TrimPrefix(input, "println(")
		content = strings.TrimSuffix(content, ")")
		content = strings.Trim(content, "\"")
		
		if val, exists := variables[content]; exists {
			fmt.Println(val)
		} else {
			fmt.Println(content)
		}
		return false
	case strings.HasPrefix(input, "LOADING(") && strings.HasSuffix(input, ")"):
		content := strings.TrimPrefix(input, "LOADING(")
		content = strings.TrimSuffix(content, ")")
		content = strings.Trim(content, "\"")
		file, err := os.Open(content)
		if err != nil {
			fmt.Println("打开文件出错:", err)
			return false
		}
		defer file.Close()
		scanner := bufio.NewScanner(file)
		lineNum := 1
		for scanner.Scan() {
			//fmt.Printf("第%d行: %s\n", lineNum, scanner.Text())
			executeCode(scanner.Text(), infoLog)
			lineNum++
		}
		if err := scanner.Err(); err != nil {
			fmt.Println("读取文件出错:", err)
		}
		return false
	case strings.Contains(input, "="):
		parts := strings.SplitN(input, "=", 2)
		if len(parts) == 2 {
			varName := strings.TrimSpace(parts[0])
			varValue := strings.TrimSpace(parts[1])
			varValue = strings.Trim(varValue, "\"")
			variables[varName] = varValue
			fmt.Printf("声明变量 %s = %s\n", varName, varValue)
		}
		return false
	default:
		if val, exists := variables[input]; exists {
			fmt.Println(val)
			return false
		}
		fmt.Printf("未知语句: %s\n", input)
		return false
	}
}

func main() {
	infoLog := log.New(os.Stdout, "INFO: ", log.Ldate|log.Ltime)

	showBanner()
	time.Sleep(2 * time.Second)
	if err := clearScreen(); err != nil {
		infoLog.Println("清屏失败:", err)
		return
	}

	fmt.Println("Welcome to ML | Version 1.0.2 | Make By MADE PLUS Studios.")
	fmt.Println("输入 'help' 获取帮助")
	fmt.Println()

	reader := bufio.NewReader(os.Stdin)
	for {
		fmt.Printf("\033[1;31;40m>>> \033[0m")
		input, err := reader.ReadString('\n')
		if err != nil {
			infoLog.Println("读取输入错误:", err)
			continue
		}

		input = strings.TrimSpace(input)
		if shouldExit := executeCode(input, infoLog); shouldExit {
			break
		}
	}
}